<template>
  <el-dialog
    v-model="visible"
    title="管理表关系"
    width="800px"
    :before-close="handleClose">
    
    <div class="relationship-dialog">
      <!-- 现有关系列表 -->
      <div class="existing-relationships">
        <div class="section-header">
          <h4>现有关系</h4>
          <el-button type="primary" size="small" @click="showCreateForm = true">
            <el-icon><Plus /></el-icon>
            创建关系
          </el-button>
        </div>
        
        <div class="relationships-list">
          <div 
            v-for="relationship in relationships" 
            :key="relationship.id"
            class="relationship-item"
            :class="{ 'active': !relationship.isActive }">
            
            <div class="relationship-info">
              <div class="relationship-main">
                <span class="table-name">{{ getTableName(relationship.fromTable) }}</span>
                <span class="field-name">[{{ getFieldName(relationship.fromTable, relationship.fromField) }}]</span>
                <el-icon class="arrow-icon"><Right /></el-icon>
                <span class="table-name">{{ getTableName(relationship.toTable) }}</span>
                <span class="field-name">[{{ getFieldName(relationship.toTable, relationship.toField) }}]</span>
              </div>
              
              <div class="relationship-details">
                <el-tag :type="getRelationshipTypeColor(relationship.type)" size="small">
                  {{ getRelationshipTypeLabel(relationship.type) }}
                </el-tag>
                <el-tag 
                  :type="relationship.crossFilterDirection === 'both' ? 'warning' : 'info'" 
                  size="small">
                  {{ relationship.crossFilterDirection === 'both' ? '双向筛选' : '单向筛选' }}
                </el-tag>
                <el-tag 
                  :type="relationship.isActive ? 'success' : 'danger'" 
                  size="small">
                  {{ relationship.isActive ? '激活' : '未激活' }}
                </el-tag>
              </div>
            </div>
            
            <div class="relationship-actions">
              <el-button size="small" text @click="editRelationship(relationship)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button 
                size="small" 
                text 
                type="danger" 
                @click="deleteRelationship(relationship.id)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          
          <div v-if="relationships.length === 0" class="empty-state">
            <el-empty description="暂无表关系" />
          </div>
        </div>
      </div>
      
      <!-- 创建/编辑关系表单 -->
      <div v-if="showCreateForm" class="create-relationship">
        <div class="section-header">
          <h4>{{ editingRelationship ? '编辑关系' : '创建关系' }}</h4>
          <el-button size="small" text @click="cancelEdit">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <el-form 
          ref="formRef" 
          :model="formData" 
          :rules="formRules" 
          label-width="120px"
          size="default">
          
          <div class="form-row">
            <div class="form-col">
              <el-form-item label="源表" prop="fromTable">
                <el-select 
                  v-model="formData.fromTable" 
                  placeholder="选择源表"
                  style="width: 100%"
                  @change="onFromTableChange">
                  <el-option 
                    v-for="table in tables" 
                    :key="table.id"
                    :label="table.name"
                    :value="table.id" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="源字段" prop="fromField">
                <el-select 
                  v-model="formData.fromField" 
                  placeholder="选择源字段"
                  style="width: 100%"
                  :disabled="!formData.fromTable">
                  <el-option 
                    v-for="field in fromTableFields" 
                    :key="field.id"
                    :label="`${field.name} (${field.dataType})`"
                    :value="field.id" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="form-divider">
              <el-icon size="24"><Right /></el-icon>
            </div>
            
            <div class="form-col">
              <el-form-item label="目标表" prop="toTable">
                <el-select 
                  v-model="formData.toTable" 
                  placeholder="选择目标表"
                  style="width: 100%"
                  @change="onToTableChange">
                  <el-option 
                    v-for="table in tables" 
                    :key="table.id"
                    :label="table.name"
                    :value="table.id" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="目标字段" prop="toField">
                <el-select 
                  v-model="formData.toField" 
                  placeholder="选择目标字段"
                  style="width: 100%"
                  :disabled="!formData.toTable">
                  <el-option 
                    v-for="field in toTableFields" 
                    :key="field.id"
                    :label="`${field.name} (${field.dataType})`"
                    :value="field.id" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          
          <el-form-item label="关系类型" prop="type">
            <el-select v-model="formData.type" style="width: 100%">
              <el-option label="一对一 (1:1)" value="one-to-one" />
              <el-option label="一对多 (1:N)" value="one-to-many" />
              <el-option label="多对多 (N:N)" value="many-to-many" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="交叉筛选方向" prop="crossFilterDirection">
            <el-radio-group v-model="formData.crossFilterDirection">
              <el-radio value="single">单向</el-radio>
              <el-radio value="both">双向</el-radio>
            </el-radio-group>
            <div class="form-tip">
              <el-text type="info" size="small">
                单向：只能从源表筛选目标表；双向：两个表可以相互筛选
              </el-text>
            </div>
          </el-form-item>
          
          <el-form-item label="关系状态">
            <el-switch 
              v-model="formData.isActive"
              active-text="激活"
              inactive-text="未激活" />
          </el-form-item>
          
          <!-- 关系验证结果 -->
          <div v-if="validationResult" class="validation-result">
            <el-alert
              :title="validationResult.message"
              :type="validationResult.valid ? 'success' : 'error'"
              :closable="false"
              show-icon />
          </div>
        </el-form>
        
        <div class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveRelationship" :loading="saving">
            {{ editingRelationship ? '更新' : '创建' }}
          </el-button>
        </div>
      </div>
      
      <!-- 关系建议 -->
      <div v-if="!showCreateForm && suggestedRelationships.length > 0" class="suggested-relationships">
        <div class="section-header">
          <h4>建议的关系</h4>
          <el-text type="info" size="small">基于字段名称和类型的智能建议</el-text>
        </div>
        
        <div class="suggestions-list">
          <div 
            v-for="suggestion in suggestedRelationships" 
            :key="`${suggestion.fromTable}_${suggestion.toTable}`"
            class="suggestion-item">
            
            <div class="suggestion-info">
              <span class="table-name">{{ getTableName(suggestion.fromTable) }}</span>
              <span class="field-name">[{{ getFieldName(suggestion.fromTable, suggestion.fromField) }}]</span>
              <el-icon class="arrow-icon"><Right /></el-icon>
              <span class="table-name">{{ getTableName(suggestion.toTable) }}</span>
              <span class="field-name">[{{ getFieldName(suggestion.toTable, suggestion.toField) }}]</span>
              
              <el-tag type="warning" size="small">{{ suggestion.confidence }}% 匹配</el-tag>
            </div>
            
            <el-button size="small" type="primary" @click="applySuggestion(suggestion)">
              应用
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useDataModelStore } from '../../stores/dataModelStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Right, 
  Edit, 
  Delete, 
  Close 
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  tables: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'relationship-created'])

// 数据模型store
const dataModelStore = useDataModelStore()

// 响应式数据
const visible = ref(false)
const showCreateForm = ref(false)
const editingRelationship = ref(null)
const formRef = ref(null)
const saving = ref(false)
const validationResult = ref(null)

const formData = ref({
  fromTable: '',
  fromField: '',
  toTable: '',
  toField: '',
  type: 'one-to-many',
  crossFilterDirection: 'single',
  isActive: true
})

// 计算属性
const relationships = computed(() => dataModelStore.relationships)

const fromTableFields = computed(() => {
  if (!formData.value.fromTable) return []
  const table = props.tables.find(t => t.id === formData.value.fromTable)
  return table?.fields || []
})

const toTableFields = computed(() => {
  if (!formData.value.toTable) return []
  const table = props.tables.find(t => t.id === formData.value.toTable)
  return table?.fields || []
})

const suggestedRelationships = computed(() => {
  // 智能建议关系
  const suggestions = []
  
  for (const table1 of props.tables) {
    for (const table2 of props.tables) {
      if (table1.id === table2.id) continue
      
      // 查找可能的关系字段
      for (const field1 of table1.fields) {
        for (const field2 of table2.fields) {
          // 检查是否已存在关系
          const existingRelation = relationships.value.find(rel => 
            (rel.fromTable === table1.id && rel.toTable === table2.id && 
             rel.fromField === field1.id && rel.toField === field2.id) ||
            (rel.fromTable === table2.id && rel.toTable === table1.id && 
             rel.fromField === field2.id && rel.toField === field1.id)
          )
          
          if (existingRelation) continue
          
          let confidence = 0
          
          // 主键-外键匹配
          if (field1.isPrimaryKey && field2.isForeignKey) {
            confidence = 90
          } else if (field2.isPrimaryKey && field1.isForeignKey) {
            confidence = 90
          }
          // 字段名匹配
          else if (field1.name.toLowerCase() === field2.name.toLowerCase()) {
            confidence = 80
          }
          // ID字段匹配
          else if (field1.name.toLowerCase() === 'id' && field2.name.toLowerCase().includes(table1.name.toLowerCase())) {
            confidence = 70
          } else if (field2.name.toLowerCase() === 'id' && field1.name.toLowerCase().includes(table2.name.toLowerCase())) {
            confidence = 70
          }
          // 数据类型匹配
          else if (field1.dataType === field2.dataType && 
                   (field1.name.toLowerCase().includes('id') || field2.name.toLowerCase().includes('id'))) {
            confidence = 60
          }
          
          if (confidence >= 60) {
            suggestions.push({
              fromTable: table1.id,
              fromField: field1.id,
              toTable: table2.id,
              toField: field2.id,
              confidence
            })
          }
        }
      }
    }
  }
  
  return suggestions.sort((a, b) => b.confidence - a.confidence).slice(0, 5)
})

const formRules = {
  fromTable: [
    { required: true, message: '请选择源表', trigger: 'change' }
  ],
  fromField: [
    { required: true, message: '请选择源字段', trigger: 'change' }
  ],
  toTable: [
    { required: true, message: '请选择目标表', trigger: 'change' }
  ],
  toField: [
    { required: true, message: '请选择目标字段', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择关系类型', trigger: 'change' }
  ]
}

// 监听器
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    resetForm()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

watch([
  () => formData.value.fromTable,
  () => formData.value.fromField,
  () => formData.value.toTable,
  () => formData.value.toField
], () => {
  validateRelationship()
})

// 方法
const resetForm = () => {
  showCreateForm.value = false
  editingRelationship.value = null
  formData.value = {
    fromTable: '',
    fromField: '',
    toTable: '',
    toField: '',
    type: 'one-to-many',
    crossFilterDirection: 'single',
    isActive: true
  }
  validationResult.value = null
}

const getTableName = (tableId) => {
  const table = props.tables.find(t => t.id === tableId)
  return table?.name || tableId
}

const getFieldName = (tableId, fieldId) => {
  const table = props.tables.find(t => t.id === tableId)
  const field = table?.fields.find(f => f.id === fieldId)
  return field?.name || fieldId
}

const getRelationshipTypeLabel = (type) => {
  const labels = {
    'one-to-one': '一对一',
    'one-to-many': '一对多',
    'many-to-many': '多对多'
  }
  return labels[type] || type
}

const getRelationshipTypeColor = (type) => {
  const colors = {
    'one-to-one': 'success',
    'one-to-many': 'primary',
    'many-to-many': 'warning'
  }
  return colors[type] || 'info'
}

const onFromTableChange = () => {
  formData.value.fromField = ''
  validateRelationship()
}

const onToTableChange = () => {
  formData.value.toField = ''
  validateRelationship()
}

const validateRelationship = () => {
  if (!formData.value.fromTable || !formData.value.fromField || 
      !formData.value.toTable || !formData.value.toField) {
    validationResult.value = null
    return
  }
  
  const relationship = {
    fromTable: formData.value.fromTable,
    fromField: formData.value.fromField,
    toTable: formData.value.toTable,
    toField: formData.value.toField
  }
  
  validationResult.value = dataModelStore.validateRelationship(relationship)
}

const editRelationship = (relationship) => {
  editingRelationship.value = relationship
  formData.value = { ...relationship }
  showCreateForm.value = true
}

const deleteRelationship = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个关系吗？', '确认删除', {
      type: 'warning'
    })
    
    dataModelStore.removeRelationship(id)
    ElMessage.success('关系删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const applySuggestion = (suggestion) => {
  formData.value = {
    fromTable: suggestion.fromTable,
    fromField: suggestion.fromField,
    toTable: suggestion.toTable,
    toField: suggestion.toField,
    type: 'one-to-many',
    crossFilterDirection: 'single',
    isActive: true
  }
  showCreateForm.value = true
}

const saveRelationship = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!validationResult.value?.valid) {
      ElMessage.error('关系验证失败，请检查字段类型是否匹配')
      return
    }
    
    saving.value = true
    
    if (editingRelationship.value) {
      // 更新关系
      dataModelStore.updateRelationship(editingRelationship.value.id, formData.value)
      ElMessage.success('关系更新成功')
    } else {
      // 创建关系
      const newRelationship = dataModelStore.addRelationship(formData.value)
      ElMessage.success('关系创建成功')
      emit('relationship-created', newRelationship)
    }
    
    cancelEdit()
  } catch (error) {
    console.error('保存关系失败:', error)
  } finally {
    saving.value = false
  }
}

const cancelEdit = () => {
  showCreateForm.value = false
  editingRelationship.value = null
  resetForm()
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.relationship-dialog {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.relationships-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.relationship-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
}

.relationship-item.active {
  opacity: 0.6;
  background: #f5f7fa;
}

.relationship-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.relationship-main {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.table-name {
  color: #409EFF;
  font-weight: 600;
}

.field-name {
  color: #606266;
  font-size: 12px;
}

.arrow-icon {
  color: #909399;
}

.relationship-details {
  display: flex;
  gap: 8px;
}

.relationship-actions {
  display: flex;
  gap: 8px;
}

.create-relationship {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.form-col {
  flex: 1;
}

.form-divider {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409EFF;
}

.form-tip {
  margin-top: 4px;
}

.validation-result {
  margin-top: 16px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.suggested-relationships {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #f8f9fa;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.suggestion-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.suggestion-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}
</style>
